<?php
    $DEBUG = false; 

    include_once "classes/User.php";
    session_start();
    include_once "session.php";
    
    if (isLoggedIn()) {
        if ($DEBUG) {
            echo "Already logged in as ";
            echo(json_encode($_SESSION["User"]->toArray()));
        }
        exit();
    }
    
    $DO_GET = $DEBUG;
    $IN = $DO_GET ? $_GET : $_POST;
    include_once "db/db_cse305.php";
    
    //Validate Input
    if (!isset($IN["user"])) {
        if ($DEBUG)
            echo "'user' not set.<br />";
        exit();
    }
    $Username = $IN["user"];
    
    if (!isset($IN["pass"])) {
        if ($DEBUG)
            echo "'pass' not set.<br />";
        exit();
    }
    $Password = $IN["pass"];
    
    $ret = array();
    
    $query = sprintf("SELECT * FROM users WHERE UserName = '%s' && Password = SHA1(CONCAT('%s', Salt))", 
            mysql_real_escape_string($Username),
            mysql_real_escape_string($Password));
    $result = mysql_query($query) or die(mysql_error());
    
    if (mysql_num_rows($result) < 1) {
        $ret["Success"] = 0;
        echo(json_encode($ret));
        exit();
    }
    
    if ($row = mysql_fetch_assoc($result)) {
        validateUser();
        
        $user = new User($row);
        $_SESSION["User"] = $user;
        
        
        
        $ret["Success"] = 1;
        $ret["User"] = $user->toArray();
        
        echo(json_encode($ret));
    }
?>
